<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2020/02/29
 * Time: 14:58
 */

namespace business\elasticsearch\services;

use business\elasticsearch\repositories\IntegrateSupplierRepository;

class SupplierRecommendService
{
    /**
     * 获取推荐列表
     * @param $pageIndex
     * @param $pageSize
     * @return array
     */
    public function getList($pageIndex, $pageSize)
    {
        $query = [];

        // 构建查询条件
        $this->builderQueryConds($query);

//        echo '<pre>';
//        var_dump($query);exit;

        $from = ($pageIndex - 1) * $pageSize;

        $include = [];

        list($total, $data) = (new IntegrateSupplierRepository())->queryList($query, $include, $from, $pageSize, [], []);

        $result = ['resultNum' => $total, 'resultSet' => null];

        if (!empty($data)) {
            foreach ($data as $dv) {
                $result['resultSet'][] = $dv['_source'];
            }
        }

        return $result;
    }

    /**
     * 构建查询条件
     * @param array $query
     */
    protected function builderQueryConds(&$query = [])
    {
        $bool = [];
        $boolKey = 0;
        $this->builderEquity($bool, $boolKey);
        !empty($bool) && $query['function_score']['query']['bool'] = $bool;
        $query['function_score']['functions'] = [
            ['filter' => ['term' => ['isDiamondSupplier' => 1]], 'weight' => 3],   //是否钻石
        ];
        $query['function_score']['boost_mode'] = 'sum';
    }

    /**
     * 构建供应商权益查询条件
     * @param array $bool
     * @param $boolKey
     */
    protected function builderEquity
    (
        &$bool = [],
        &$boolKey
    ) {
        $keys = ['isDiamondSupplier', 'isPlatinumSupplier'];
        if (!empty($keys)) {
            array_walk($keys,
                function
                (
                    $value
                )
                use (
                    &$bool,
                    $boolKey
                ) {
                    $bool['filter']['bool']['must'][$boolKey]['bool']['should'][] = [
                        'term' => [
                            $value => 1
                        ]
                    ];
                }
            );
            $boolKey++;
        }
    }
}
